package com.youchuang.aspect;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;


@Aspect
@Component
/**
 *  Action的切面
 */
public class ActionAspect {
    private static final Logger logger = Logger.getLogger(ActionAspect.class.getSimpleName());

    @Pointcut("execution(* com.youchuang.action.*.*.*Action(..))")
    private void theMethod() {
    }

    @Around("theMethod()")
    public Object openRedisTx(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        String targetName = pjp.getTarget().getClass().getSimpleName();
        logger.info(method.getName() + " will be execute and target is of class [" + targetName + "]");
        Object obj = pjp.proceed();
        return obj;
    }

    @AfterThrowing(pointcut = "theMethod()", throwing = "e")
    public void rollbackTx(JoinPoint jp, Exception e) {
        if (e != null) {
            String targetName = jp.getTarget().getClass().getName();
            logger.error("执行异常, 发生在类[" + targetName + "]");
        }
    }
}
